// 📡 Ping 消息处理器
import type { PlasmoMessaging } from "@plasmohq/messaging"

// 类型定义
type PingRequest = { timestamp: number; userId?: string; message?: string }
type PingResponse = { message: string; serverTime: number; echo?: string }
type ApiResponse<T = any> = { success: boolean; data?: T; error?: { code: string; message: string; details?: any } }

/**
 * Ping 消息处理器 - 用于测试连接和响应时间
 * 
 * @param req - 包含 timestamp, userId, message 的请求
 * @param res - 响应对象
 */
const handler: PlasmoMessaging.MessageHandler<PingRequest, ApiResponse<PingResponse>> = async (req, res) => {
  console.log("📨 收到 ping 消息:", req.body)
  
  try {
    const { timestamp, userId, message } = req.body
    const serverTime = Date.now()
    const responseTime = serverTime - timestamp
    
    // 模拟一些处理时间
    await new Promise(resolve => setTimeout(resolve, 100))
    
    const response: PingResponse = {
      message: "pong",
      serverTime: Date.now(),
      echo: message || `Hello ${userId || 'Anonymous'}! Response time: ${responseTime}ms`
    }
    
    res.send({
      success: true,
      data: response
    })
    
    console.log("📤 发送 pong 响应:", response)
    
  } catch (error) {
    console.error("❌ Ping 处理错误:", error)
    res.send({
      success: false,
      error: {
        code: "PING_ERROR",
        message: "处理 ping 消息时发生错误",
        details: error.message
      }
    })
  }
}

export default handler